<?php
// +----------------------------------------------------------------------
// | Created by PHPstorm: [ JRK丶Admin ]
// +----------------------------------------------------------------------
// | Copyright (c) 2019~2022 [LuckyHHY] All rights reserved.
// +----------------------------------------------------------------------
// | SiteUrl: http://www.luckyhhy.cn
// +----------------------------------------------------------------------
// | Author: LuckyHhy <jackhhy520@qq.com>
// +----------------------------------------------------------------------
// | Date: 2020-08-07 12:33:37
// +----------------------------------------------------------------------
// | Description:
// +----------------------------------------------------------------------

namespace app\admin\controller;
use app\admin\model\Commands;
use app\common\controller\AdminBaseController;
use think\Exception;
use think\facade\Db;
use app\common\service\FormBuilder as Form;
use think\facade\Route;
use app\admin\service\ExcelService;
use think\Request;
use think\console\Input;
use think\console\Output;
use app\command\JrkadminCurd;

class Command extends AdminBaseController
{

    protected function initialize()
   {
           parent::initialize(); // TODO: Change the autogenerated stub

           $this->model = new Commands();
    }


    /**
     * @param Request $request
     * @return string|\think\response\Json
     * @throws \Exception
     * @author: LuckyHhy <jackhhy520@qq.com>
     * @describe:添加
     */
    public function add(Request $request){
        if (IS_AJAX) {
            $data = $request->post();
            try{
                $data['command']="php think make:jrkadmin_curd ".$data['controller']." ".$data['model']." ".$data['validate']." --app ".$data['app']."";
                return parent::JsonReturn("生成命令成功",1,"",['data'=>$data['command']]);
            }catch (Exception $exception){
                return parent::JsonReturn($exception->getMessage(), 0);
            }
        }
        return $this->fetch();
    }


    /**
     * @param Request $request
     * @return \think\response\Json
     * @throws \Exception
     * @author: LuckyHhy <jackhhy520@qq.com>
     * @describe:执行命令
     */
    public function do(Request $request){
        if (IS_AJAX) {
            $data = $request->post();
            try{
               // dd($data);
                if (empty($data['command'])){
                    return parent::JsonReturn("请先生成命令行", 0);
                }
                $data['admin_id']=self::$admin_info["id"];
                $data['name']="生成菜单";
                $data['do_time']=date("Y-m-d H:i:s",time());
                $data["ext"]=json_encode([$data['controller'],$data['model'],$data['validate'],"--app",$data['app']]);
                $res= $this->model->create($data);
                if ($res){
                    $com=new JrkadminCurd();
                    $input = new Input(json_decode($data["ext"],true));
                    $output=new Output();
                    $com->run($input,$output);
                    return parent::JsonReturn("命令执行成功");
                }else{
                    return parent::JsonReturn("生成命令保存失败", 0);
                }
            }catch (Exception $exception){
                return parent::JsonReturn($exception->getMessage(), 0);
            }
        }

    }


    /**
     * @param Commands $commands
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * @author: LuckyHhy <jackhhy520@qq.com>
     * @describe:导出
     */
    public function export(Commands $commands){
        $param=$this->request->post();
        $where=[];
        $order = 'id desc';

        if (!empty($param['status'])){
            $status=(int)$param['status'];
            $where[] = ['status', '=', $status];
        }

        if (!empty($param['admin_id'])){
            $admin_id=(int)$param['admin_id'];
            $where[] = ['admin_id', '=', $admin_id];
        }
        if (!empty($param['isAsc']) && !empty($param['orderByColumn'])) {
            $order = "{$param['orderByColumn']} {$param['isAsc']}";
        }

        if (isset($param['time']) && $param['time'] != '') {
            $ck = @explode(" ~ ", $param['time']);
            $b = $ck[0] . " 00:00:00";
            $e = $ck[1] . " 23:59:59";
            $where[] = ['create_time', 'between', [strtotime($b), strtotime($e)]];
        }

        $result=$commands->where($where)->order($order)->select()->toArray();
        if (empty($result)){
            return parent::JsonReturn("根据条件未查询到数据",0);
        }

        $arr=[];
        $s=[0=>'失败',1=>'成功'];
        foreach ($result as $k=>$v){
            $arr[]=[
                $v['id'],$v['name'],$v['app'],$v['command'],$v['controller'], $v['model'],$v['validate'],$v['do_time'],$s[$v['status']],$v['create_time']
            ];
        }
        $filename= ExcelService::setExcelHeader(['ID','名称','模块名','命令行','控制器','模型名','验证器','执行时间','状态','添加时间'])
            ->setExcelTile('在线命令', '在线命令数据',date('Y-m-d H:i:s',time()))
            ->setExcelContent($arr)
            ->ExcelReturn();
        return parent::JsonReturn($filename);
    }


}